<!<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>橡皮筋 拉线</title>

    <style type="text/css">
        body{
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>

    <canvas id="canvas" width=400 height=400>
        Canvas not supported
    </canvas>


    <script type="text/javascript">
        var canvas = document.getElementById("canvas"),
            context = canvas.getContext("2d");

        window.onload = function(){
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        }

        

        var startP = {},
            dragging = false,
            surface = null;


        function windowToCanvas(e){
            var bbox = canvas.getBoundingClientRect();
            return {
                x:e.clientX - bbox.left*(canvas.width/bbox.width),
                y:e.clientY - bbox.top*(canvas.height/bbox.height)
            }
        }

        function saveDrawingSurface(){
            surface = context.getImageData(0, 0, canvas.width, canvas.height);
        }

        function restoreDrawingSurface(){
            context.putImageData(surface, 0, 0);
        }

        function drawLine(p){
            context.beginPath();
            context.moveTo(startP.x, startP.y);
            context.lineTo(p.x, p.y);
            context.stroke();
        }

        function draw(p){
            drawLine(p);
        }

        canvas.onmousedown = function(e){
            e.preventDefault();
            dragging = true;
            startP = windowToCanvas(e);
            saveDrawingSurface();
        }

        canvas.onmousemove = function(e){
            e.preventDefault();
            if (dragging){
                p = windowToCanvas(e);
                restoreDrawingSurface();
                draw(p);
            }
        }

        canvas.onmouseup = function(e){
            dragging = false;
            p = windowToCanvas(e);
            restoreDrawingSurface();
            draw(p);
        }

    </script>
</body>
</html>